package com.example.launibleplugin

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import android.app.AlertDialog
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.example.launibleplugin.constants.BluetoothConstants
import com.example.launibleplugin.listener.SimpleBluetoothEventListener
import com.example.launibleplugin.model.BluetoothDevice
import com.example.launibleplugin.model.ConnectionInfo
import com.example.launibleplugin.model.DataRecord
import com.example.launibleplugin.ui.theme.LaUniBlePluginTheme
import com.example.launibleplugin.ui.components.DeviceScannerComponent
import com.example.launibleplugin.ui.components.MeasurementControlComponent
import com.example.launibleplugin.ui.components.MeasurementDataDisplayComponent
import com.example.launibleplugin.protocol.ProtocolMessage
import com.example.launibleplugin.utils.Logger
import com.example.launibleplugin.utils.LogLevel
import com.google.gson.Gson

/**
 * 主活动 - 呼吸家蓝牙插件演示应用
 * Function: 演示插件的基本功能和使用方法
 * Note: 包含设备扫描、连接、数据接收等功能演示
 */
class MainActivity : ComponentActivity() {
    
    private lateinit var plugin: LaUniBlePlugin
    private val gson = Gson()
    
    // 权限请求
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        if (allGranted) {
            Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "需要所有权限才能正常使用", Toast.LENGTH_LONG).show()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        
        // 初始化日志
        Logger.initialize(
            logDir = getExternalFilesDir("logs"),
            enableFile = true,
            minLevel = LogLevel.DEBUG
        )
        
        // 初始化插件
        plugin = LaUniBlePlugin.getInstance(this)
        
        // 请求权限
        requestBluetoothPermissions()
        
        setContent {
            LaUniBlePluginTheme {
                BluetoothPluginDemo(plugin)
            }
        }
    }
    
    /**
     * Function: 请求蓝牙权限
     * Note: 根据Android版本请求相应的蓝牙权限
     */
    private fun requestBluetoothPermissions() {
        val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            BluetoothConstants.BLUETOOTH_PERMISSIONS_API31
        } else {
            BluetoothConstants.BLUETOOTH_PERMISSIONS
        }
        
        val missingPermissions = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }
        
        if (missingPermissions.isNotEmpty()) {
            requestPermissionLauncher.launch(missingPermissions.toTypedArray())
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        plugin.cleanup()
    }
}

/**
 * 蓝牙插件演示界面
 * Function: 提供插件功能的可视化演示
 * Parameter: plugin - 插件实例
 * Note: 使用Compose构建的演示界面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BluetoothPluginDemo(plugin: LaUniBlePlugin) {
    var isInitialized by remember { mutableStateOf(false) }
    var connectedDevices by remember { mutableStateOf(listOf<String>()) }
    var receivedData by remember { mutableStateOf(listOf<String>()) }
    var statusMessage by remember { mutableStateOf("准备就绪") }
    var connectedDevice by remember { mutableStateOf<com.example.launibleplugin.model.BluetoothDevice?>(null) }
    var isConnected by remember { mutableStateOf(false) }
    var protocolMessages by remember { mutableStateOf(listOf<ProtocolMessage>()) }
    
    val context = LocalContext.current
    
    // 设置事件监听器
    LaunchedEffect(Unit) {
        
        plugin.setEventCallback("onDeviceConnected") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                val device = data?.get("device") as? Map<String, Any>
                val deviceId = device?.get("deviceId") as? String
                val deviceName = device?.get("deviceName") as? String
                val macAddress = device?.get("macAddress") as? String
                
                if (deviceId != null && macAddress != null) {
                    connectedDevices = connectedDevices + deviceId
                    connectedDevice = com.example.launibleplugin.model.BluetoothDevice(
                        deviceId = deviceId,
                        deviceName = deviceName,
                        macAddress = macAddress,
                        signalStrength = 0
                    )
                    isConnected = true
                    statusMessage = "设备已连接: ${deviceName ?: deviceId}"
                    
                    Logger.i("MainActivity", "✅ 设备连接成功: $deviceName ($macAddress)")
                }
            } catch (e: Exception) {
                Logger.e("MainActivity", "解析设备连接事件失败", e)
            }
        }
        
        plugin.setEventCallback("onDeviceDisconnected") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                val device = data?.get("device") as? Map<String, Any>
                val deviceId = device?.get("deviceId") as? String
                
                if (deviceId != null) {
                    connectedDevices = connectedDevices.filter { it != deviceId }
                    if (connectedDevice?.deviceId == deviceId) {
                        connectedDevice = null
                        isConnected = false
                    }
                    statusMessage = "设备已断开: $deviceId"
                    
                    Logger.i("MainActivity", "❌ 设备连接断开: $deviceId")
                }
            } catch (e: Exception) {
                Logger.e("MainActivity", "解析设备断开事件失败", e)
            }
        }
        
        // 添加连接状态变化监听
        plugin.setEventCallback("onConnectionStateChanged") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                val deviceId = data?.get("deviceId") as? String
                val state = data?.get("state") as? String
                
                Logger.d("MainActivity", "连接状态变化: $deviceId -> $state")
                
                if (deviceId != null && connectedDevice?.deviceId == deviceId) {
                    when (state) {
                        "CONNECTED" -> {
                            isConnected = true
                            statusMessage = "设备已连接: ${connectedDevice?.getDisplayName()}"
                            Logger.i("MainActivity", "✅ 连接状态同步: $deviceId -> CONNECTED")
                        }
                        "DISCONNECTED" -> {
                            isConnected = false
                            statusMessage = "设备已断开: ${connectedDevice?.getDisplayName()}"
                            Logger.i("MainActivity", "❌ 连接状态同步: $deviceId -> DISCONNECTED")
                        }
                        "CONNECTING" -> {
                            statusMessage = "正在连接: ${connectedDevice?.getDisplayName()}"
                            Logger.d("MainActivity", "🔄 连接状态同步: $deviceId -> CONNECTING")
                        }
                        "ERROR" -> {
                            isConnected = false
                            statusMessage = "连接错误: ${connectedDevice?.getDisplayName()}"
                            Logger.e("MainActivity", "❌ 连接状态同步: $deviceId -> ERROR")
                        }
                    }
                }
            } catch (e: Exception) {
                Logger.e("MainActivity", "解析连接状态变化事件失败", e)
            }
        }
        
        plugin.setEventCallback("onDataReceived") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                if (data != null) {
                    val dataType = data["dataType"] as? String ?: "未知"
                    val timestamp = data["timestamp"] as? Double ?: 0.0
                    val dataPoints = data["dataPoints"] as? List<Map<String, Any>> ?: emptyList()
                    
                    val dataInfo = "[$dataType] ${dataPoints.joinToString(", ") { 
                        val point = it as Map<String, Any>
                        "${point["metricName"]}: ${point["formattedValue"]}"
                    }}"
                    
                    receivedData = (receivedData + dataInfo).takeLast(20)
                    statusMessage = "接收到数据: $dataType"
                }
            } catch (e: Exception) {
                Logger.e("MainActivity", "解析数据接收事件失败", e)
            }
        }
        
        plugin.setEventCallback("onError") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                val errorMessage = data?.get("errorMessage") as? String ?: "未知错误"
                statusMessage = "错误: $errorMessage"
            } catch (e: Exception) {
                statusMessage = "发生未知错误"
            }
        }
        
        // 添加协议消息接收回调
        plugin.setEventCallback("onProtocolMessageReceived") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                val messageType = data?.get("messageType") as? String
                val deviceId = data?.get("deviceId") as? String
                
                Logger.d("MainActivity", "收到协议消息: $messageType from $deviceId")
                
                when (messageType) {
                    "AxDateMessage" -> {
                        val command = data["command"] as? String ?: ""
                        val param1 = (data["param1"] as? Double)?.toInt() ?: 0
                        val param2 = (data["param2"] as? Double)?.toInt() ?: 0
                        val param3 = (data["param3"] as? Double)?.toInt() ?: 0
                        val timeData = data["timeData"] as? String ?: ""
                        val checksum = data["checksum"] as? String ?: ""
                        
                        val axDateMessage = com.example.launibleplugin.protocol.AxDateMessage(
                            command = command,
                            param1 = param1,
                            param2 = param2,
                            param3 = param3,
                            timeData = timeData,
                            checksum = checksum
                        )
                        
                        protocolMessages = (protocolMessages + axDateMessage).takeLast(50)
                        statusMessage = "收到日期时间数据: ${timeData}"
                        Logger.d("MainActivity", "协议消息列表更新，当前数量: ${protocolMessages.size}")
                        Logger.d("MainActivity", "最新日期数据: ${timeData}")
                    }
                    "AxFvcMessage" -> {
                        val command = data["command"] as? String ?: ""
                        val testNumber = (data["testNumber"] as? Double)?.toInt() ?: 0
                        val testCount = (data["testCount"] as? Double)?.toInt() ?: 0
                        val pef = data["pef"] as? Double ?: 0.0
                        val fev1 = data["fev1"] as? Double ?: 0.0
                        val fev025 = data["fev025"] as? Double ?: 0.0
                        val fvc = data["fvc"] as? Double ?: 0.0
                        val mef75 = data["mef75"] as? Double ?: 0.0
                        val mef50 = data["mef50"] as? Double ?: 0.0
                        val mef25 = data["mef25"] as? Double ?: 0.0
                        val mmef = data["mmef"] as? Double ?: 0.0
                        val fev1_fvc = data["fev1_fvc"] as? Double ?: 0.0
                        val fet = data["fet"] as? Double ?: 0.0
                        val temperature = data["temperature"] as? Double ?: 0.0
                        val pressure = (data["pressure"] as? Double)?.toInt() ?: 0
                        val humidity = (data["humidity"] as? Double)?.toInt() ?: 0
                        val reserved1 = (data["reserved1"] as? Double)?.toInt() ?: 0
                        val heartRate = (data["heartRate"] as? Double)?.toInt() ?: 0
                        val oxygenSaturation = (data["oxygenSaturation"] as? Double)?.toInt() ?: 0
                        val testQuality = (data["testQuality"] as? Double)?.toInt() ?: 0
                        val checksum = data["checksum"] as? String ?: ""
                        
                        val axFvcMessage = com.example.launibleplugin.protocol.AxFvcMessage(
                            command = command,
                            testNumber = testNumber,
                            testCount = testCount,
                            pef = pef,
                            fev1 = fev1,
                            fev025 = fev025,
                            fvc = fvc,
                            mef75 = mef75,
                            mef50 = mef50,
                            mef25 = mef25,
                            mmef = mmef,
                            fev1_fvc = fev1_fvc,
                            fet = fet,
                            temperature = temperature,
                            pressure = pressure,
                            humidity = humidity,
                            reserved1 = reserved1,
                            heartRate = heartRate,
                            oxygenSaturation = oxygenSaturation,
                            testQuality = testQuality,
                            checksum = checksum
                        )
                        
                        protocolMessages = (protocolMessages + axFvcMessage).takeLast(50)
                        statusMessage = "收到FVC测量数据: PEF=${String.format("%.2f", pef)}, FEV1=${String.format("%.2f", fev1)}"
                        Logger.d("MainActivity", "协议消息列表更新，当前数量: ${protocolMessages.size}")
                        Logger.d("MainActivity", "最新FVC数据: PEF=$pef, FEV1=$fev1, FVC=$fvc")
                    }
                }
            } catch (e: Exception) {
                Logger.e("MainActivity", "解析协议消息事件失败", e)
                statusMessage = "协议消息解析失败: ${e.message}"
            }
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("呼吸家蓝牙插件演示") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer
                )
            )
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 状态信息
            item {
                Card {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "状态信息",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                        Text(text = statusMessage)
                        Text(text = "已连接设备: ${connectedDevices.size}")
                        if (isConnected && connectedDevice != null) {
                            Text(
                                text = "当前设备: ${connectedDevice!!.getDisplayName()}",
                                color = MaterialTheme.colorScheme.primary,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }
                }
            }
            
            // 控制按钮
            item {
                Card {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "控制操作",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Button(
                                onClick = {
                                    if (!isInitialized) {
                                        val result = plugin.initialize()
                                        isInitialized = true
                                        statusMessage = "插件已初始化"
                                    }
                                },
                                enabled = !isInitialized,
                                modifier = Modifier.weight(1f)
                            ) {
                                Text("初始化")
                            }
                            
                            Button(
                                onClick = {
                                    try {
                                        val statusResult = plugin.checkBluetoothStatus()
                                        val response = Gson().fromJson(statusResult, Map::class.java)
                                        val success = response["success"] as? Boolean ?: false
                                        
                                        if (success) {
                                            val data = response["data"] as? Map<String, Any>
                                            if (data != null) {
                                                val bluetoothAvailable = data["bluetoothAvailable"] as? Boolean ?: false
                                                val hasPermissions = data["hasPermissions"] as? Boolean ?: false
                                                val connectedCount = (data["connectedDevices"] as? Double)?.toInt() ?: 0
                                                
                                                val statusText = buildString {
                                                    append("蓝牙状态: ")
                                                    if (bluetoothAvailable) {
                                                        append("可用")
                                                    } else {
                                                        append("不可用")
                                                    }
                                                    append(", 权限: ")
                                                    if (hasPermissions) {
                                                        append("已授权")
                                                    } else {
                                                        append("未授权")
                                                    }
                                                    append(", 已连接: ${connectedCount}个设备")
                                                    
                                                    // 添加问题提示
                                                    if (!bluetoothAvailable) {
                                                        append("\n⚠️ 请开启蓝牙功能")
                                                    }
                                                    if (!hasPermissions) {
                                                        append("\n⚠️ 请授予蓝牙权限")
                                                    }
                                                }
                                                statusMessage = statusText
                                                
                                                // 如果蓝牙不可用，弹出对话框提示用户开启蓝牙
                                                if (!bluetoothAvailable) {
                                                    val activity = context as? androidx.activity.ComponentActivity
                                                    activity?.let {
                                                        AlertDialog.Builder(it)
                                                            .setTitle("蓝牙未开启")
                                                            .setMessage("检测到蓝牙功能未开启，是否前往设置开启蓝牙？")
                                                            .setPositiveButton("去开启") { _, _ ->
                                                                val intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
                                                                it.startActivity(intent)
                                                            }
                                                            .setNegativeButton("取消", null)
                                                            .show()
                                                    }
                                                }
                                            } else {
                                                statusMessage = "蓝牙状态检查完成，但数据格式异常"
                                            }
                                        } else {
                                            val message = response["message"] as? String ?: "未知错误"
                                            statusMessage = "蓝牙状态检查失败: $message"
                                        }
                                    } catch (e: Exception) {
                                        Logger.e("MainActivity", "解析蓝牙状态失败", e)
                                        statusMessage = "蓝牙状态检查失败: ${e.message}"
                                    }
                                },
                                enabled = isInitialized,
                                modifier = Modifier.weight(1f)
                            ) {
                                Text("检查状态")
                            }
                        }
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Button(
                            onClick = {
                                val result = plugin.getConnectedDevices()
                                statusMessage = "已获取连接设备列表"
                            },
                            enabled = isInitialized,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text("连接列表")
                        }
                    }
                }
            }
            
            // 测量控制组件 - 放在设备扫描上方，连接后更显眼
            item {
                MeasurementControlComponent(
                    plugin = plugin,
                    connectedDevice = connectedDevice,
                    isConnected = isConnected
                )
            }
            
            // 测量数据展示组件
            item {
                MeasurementDataDisplayComponent(
                    measurementData = protocolMessages
                )
            }
            
            // 调试按钮 - 测试协议解析
            item {
                Card {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "调试功能",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Button(
                            onClick = {
                                // 测试协议解析
                                val testData = "#db_ax_fvc,21,125,0.63,1.31,0.26,1.55,0.75,0.26,1.27,0.83,0.83,0.14,41.88,1006,0,0,80,60,4,2D05"
                                Logger.d("MainActivity", "测试协议解析: $testData")
                                
                                val protocolHandler = com.example.launibleplugin.protocol.RespiratoryProtocolHandler()
                                val result = protocolHandler.parseProtocolMessage(testData)
                                
                                if (result != null) {
                                    protocolMessages = (protocolMessages + result).takeLast(50)
                                    statusMessage = "测试数据解析成功，协议消息数量: ${protocolMessages.size}"
                                    Logger.d("MainActivity", "测试解析成功: $result")
                                } else {
                                    statusMessage = "测试数据解析失败"
                                    Logger.e("MainActivity", "测试解析失败")
                                }
                            },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text("测试协议解析")
                        }
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Button(
                            onClick = {
                                protocolMessages = emptyList()
                                statusMessage = "已清空测量数据"
                            },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text("清空数据")
                        }
                    }
                }
            }
            
            // 设备扫描组件
            item {
                DeviceScannerComponent(
                    plugin = plugin,
                    onDeviceSelected = { device ->
                        // 在控制台输出点击连接的设备名称
                        android.util.Log.d("MainActivity", "用户点击连接设备: 名称='${device.deviceName ?: "未知设备"}', MAC='${device.macAddress}', 显示名称='${device.getDisplayName()}'")
                        
                        val deviceInfo = mapOf(
                            "deviceId" to device.deviceId,
                            "macAddress" to device.macAddress,
                            "deviceName" to device.deviceName,
                            "autoReconnect" to true
                        )
                        plugin.connectDevice(Gson().toJson(deviceInfo))
                        statusMessage = "正在连接设备: ${device.getDisplayName()}"
                    },
                    isInitialized = isInitialized
                )
            }
            
            // 接收的数据
            if (receivedData.isNotEmpty()) {
                item {
                    Text(
                        text = "接收的数据",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                }
                
                items(receivedData.reversed()) { data ->
                    Card {
                        Text(
                            text = data,
                            modifier = Modifier.padding(12.dp),
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                }
            }
        }
    }
}